<?php

namespace App\Console\Commands;

use App\Enum\CodeEnum;
use App\Enum\TravelEnum;
use App\Models\ActivityModel;
use App\Models\DriverModel;
use App\Models\ScheduleRecordModel;
use App\Services\QrcodeService;
use Illuminate\Console\Command;

class ActivityQrcodeGenerateCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'qrcode:activity';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '生成活动的qrcode';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        // 找到上次的记录，继续执行
        $record = ScheduleRecordModel::query()->where(['schedule'=>'activity-qrcode-generate'])->first();
        if( empty($record) ) {
            $this->error('ActivityQrcodeGenerateCommand: could not find the row of <b>activity-qrcode-generate</b>');
        }
        $recordId = $record['record_id'];
        $scheduleId = $record['id'];

        $row =  ActivityModel::query()->where('id','>', $recordId)->orderBy('id')->first();
        if( !empty($row) ){
            try {
                // 生成活动二维码
                $url = sprintf(TravelEnum::QRCODE_INFO_URL[TravelEnum::QRCODE_TYPE_ACTIVITY], env('BASE_URL'), $row->id);
                $row->qrcode_url = QrcodeService::getQrcode($url, $row->id, 'qrcode/'.env('APP_ENV'));
                $row->save();

                // 记录本次操作的记录位置 
                $record->record_id = $row->id;
                $record->save();

            } catch (\Exception $e) {
                $this->info($e->getMessage());
                return 0;
            }
        }

        return 0;
    }
}
